﻿namespace Mueller.CoffeeMonitor

open System
open System.Runtime.Serialization
open System.IO
open System.IO.IsolatedStorage

[<DataContract>]
type private SettingsV1 = {
    [<field: DataMember(Name = "Minify")>]
    Minify : bool

    [<field: DataMember(Name = "CreateWrapper")>]
    CreateWrapper : bool
    
    [<field: DataMember(Name = "Paths")>]
    Paths  : string array
    
    [<field: DataMember(Name = "FormLocation")>]
    FormLocation : System.Drawing.Point option
}

[<DataContract>]
type SettingsV2 = {
    [<field: DataMember(Name = "Minify")>]
    Minify : bool

    [<field: DataMember(Name = "CreateWrapper")>]
    CreateWrapper : bool

    [<field: DataMember(Name = "Iced")>]
    Iced : bool
    
    [<field: DataMember(Name = "Paths")>]
    Paths  : list<string * string option>
    
    [<field: DataMember(Name = "SettingsLocation")>]
    SettingsLocation : System.Drawing.Point option
}

module Settings =
    let private v1SettingsFile = "CoffeeMonitor.json"
    let private v2SettingsFile = "CoffeeMonitor.v2.json"

    let private getStore () =
        if isNull AppDomain.CurrentDomain.ActivationContext then
            IsolatedStorageFile.GetUserStoreForAssembly() // running stand-alone
        else
            IsolatedStorageFile.GetUserStoreForApplication() // running as click-once

    let private loadFile<'a> (store:IsolatedStorageFile) fileName =
        if store.FileExists fileName then
            let serializer = Json.DataContractJsonSerializer(typeof<'a>)
            use fs = new IsolatedStorageFileStream(fileName, FileMode.Open, store)
            Some(serializer.ReadObject(fs) :?> 'a)
        else
            None
    
    let save (settings: SettingsV2) =
        let serializer = Json.DataContractJsonSerializer(typeof<SettingsV2>)
        use store = getStore()
        use fs = new IsolatedStorageFileStream(v2SettingsFile, FileMode.Create, store)
        serializer.WriteObject(fs, settings)
    
    let load () =
        use store = getStore()
        match loadFile<SettingsV2> store v2SettingsFile with
        | Some v2 -> v2
        | None ->
            match loadFile<SettingsV1> store v1SettingsFile with
            | Some v1 ->
                { Minify = v1.Minify; CreateWrapper = v1.CreateWrapper; 
                  Iced = false; SettingsLocation = v1.FormLocation;
                  Paths = [ for path in v1.Paths -> (path, Some path) ] }
            | None ->
                { Minify = false; CreateWrapper = true; Iced = false; Paths = []; SettingsLocation = None }

